#!/usr/bin/env python
import sys
sys.path.append("/work/opt/analytic/my_python")
from lib.format_time import *
from lib.HandleMysql import *
from lib.switch_code import *
from lib.load_data import *
from jpype import *
import glob
import re
import os
reload(sys)
sys.setdefaultencoding('utf-8')

class CMCService(object):
    def __init__(self):
        self.jars = ':'.join(glob.glob('/work/opt/analytic/my_python/java_lib/cmc/*.jar'))
        self.jvm_path = '/opt/soft/java/jre/lib/amd64/server/libjvm.so'
        startJVM(self.jvm_path,"-ea","-Djava.class.path=%s" % self.jars)
        self.SCFInit =JClass("com.bj58.spat.scf.client.SCFInit")
        self.SCFInit.init('/work/opt/analytic/my_python/java_lib/cmc/scf.config')
        
        URL_disp_cate= "tcp://cmc/DispCategoryService"            
        self.ProxyFactory =JClass("com.bj58.spat.scf.client.proxy.builder.ProxyFactory")
        self.disp_cate =JClass("com.bj58.sfft.cmc.contract.IDispCategoryService")
        self.disp_cate_proxy = self.ProxyFactory.create(self.disp_cate,URL_disp_cate)
        #print "ok"
        
        URL_cate = "tcp://cmc/CategoryService"            
        self.cate =JClass("com.bj58.sfft.cmc.contract.ICategoryService")
        self.cate_proxy = self.ProxyFactory.create(self.cate,URL_cate)
        #print "ok"
        
        URL_local = "tcp://cmc/LocalService"            
        self.local =JClass("com.bj58.sfft.cmc.contract.ILocalService")
        self.local_proxy = self.ProxyFactory.create(self.local,URL_local)
        #print "ok"
        
        URL_disp_local = "tcp://cmc/DispLocalService2"            
        self.disp_local =JClass("com.bj58.sfft.cmc.contract.IDispLocalService2")
        self.disp_local_proxy = self.ProxyFactory.create(self.disp_local,URL_disp_local)
        #print "ok"
        
    def get_disp_cate(self,dcateid):
        self.query = "pid=%s"%dcateid
        #print self.query
        self.dist_cate_list = self.disp_cate_proxy.GetDispCategory(self.query,"dispcategoryid asc")
        #rint self.query
        return self.dist_cate_list
    
    def get_cate(self,cateid):
        self.query = "pid=%s"%cateid
        #print self.query
        self.cate_list = self.cate_proxy.GetCategory(self.query,"cateid asc")
        #print self.query
        return self.cate_list
    
    def get_local(self,localid):
        self.query = "pid=%s"%localid
        #print self.query
        self.local_list = self.local_proxy.GetLocal(self.query,"localid asc")
        #print self.query
        return self.local_list
    
    def get_disp_local(self,dlocalid):
        self.query = "pid=%s"%dlocalid
        #print self.query
        self.disp_local_list = self.disp_local_proxy.GetDispLocal(self.query,"displocalid asc")
        #print self.query
        return self.disp_local_list
    
    def shut_down(self):
        shutdownJVM()
    
    
#mysql - stats
def set_stat_conn():    
    conn = HandleMysql('10.5.20.16','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_groupbuy_stats')
    conn.connect()
    return conn
#mysql - 58
def set_58_conn():    
    conn = HandleMysql('10.5.20.16','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_58_stats')
    conn.connect()
    return conn
#mysql - dict
def set_dict_conn():    
    conn = HandleMysql('10.5.20.16','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_base_dicts')
    conn.connect()
    return conn

#logic
def get_cmc( s58,param,date ):
    conn = set_stat_conn();
    dict_conn = set_dict_conn()
    conn58 = set_58_conn()
    
    stat_table = "t_%s"%param
    max_id = 0
    line_list = []
    if param == "dispcategory":
        get_disp_cate(max_id,s58,line_list)
    elif param == "category":
        get_cate(max_id,s58,line_list)
    elif param == "local":
        get_local(max_id,s58,line_list)
    elif param == "displocal":
        get_disp_local(max_id,s58,line_list)
        
    cont = '\n'.join(line_list)
    path = "/work/opt/analytic/lh_tmp_data/cmc/"
    file_name = "%s_%s.txt"%(param,date.replace('-',""))
    
    writeTextToFile(path,file_name,"w",cont)
    
    #print file_path
    query = "truncate table %s;"%stat_table
    #print query
    conn.execute_sql(query)
    conn58.execute_sql(query)
    dict_conn.execute_sql(query)    

    file_path = "%s%s"%(path,file_name)
    load_data(conn,file_path,stat_table,'\t')
    load_data(conn58,file_path,stat_table,'\t')
    load_data(dict_conn,file_path,stat_table,'\t')
    
    conn.close()
    dict_conn.close()
    conn58.close()
    #s58.shut_down()
def get_disp_cate( pid,s58,line_list):
    dist_cate_list = s58.get_disp_cate(pid)
    #print len(cate_list)
    for info in dist_cate_list:
        dcate_id =info.getDispCategoryID()
        pid = info.getPID()
        cate_name = info.getCateName()
        group = info.getDispCategoryGroup()
        depth= info.getDepth()
        fullpath = info.getFullPath()
        order = info.getOrder()
        cate_id = info.getCateID()
        filter_str = info.getFilter()
        listname = info.getListName()
        system = info.getSystem()
        type_val = info.getType()
        isvisible = info.getIsVisible()
        
        param=["%s"%dcate_id,"%s"%pid,cate_name,"%s"%group,"%s"%depth,fullpath,"%s"%order,"%s"%cate_id,filter_str,listname,"%s"%system,"%s"%type_val,"%s"%isvisible]
        line_list.append('\t'.join(param))
        
        get_disp_cate(dcate_id,s58,line_list)
        
    return line_list
    
def get_cate( pid,s58,line_list ):    
    cate_list = s58.get_cate(pid)
    for info in cate_list:
        cate_id =info.getCateID()
        pid = info.getPID()
        cate_name = info.getCateName()
        depth= info.getDepth()
        fullpath = info.getFullPath()
        dirname = info.getDirName()
        
#	print "ok"        
        param=["%s"%cate_id,"%s"%pid,cate_name,dirname,"%s"%depth,fullpath]
#	print param
        line_list.append('\t'.join(param))
        get_cate(cate_id,s58,line_list)
        
def get_local( pid,s58,line_list ):    
    local_list = s58.get_local(pid)
    for info in local_list:
        local_id =info.getLocalID()
        pid = info.getPid()
        local_name = info.getLocalName()
        depth= info.getDepth()
        fullpath = info.getFullPath()
        dirname = info.getDirName()
        
        param=["%s"%local_id,"%s"%pid,local_name,fullpath,dirname,'',"%s"%depth]
        line_list.append('\t'.join(param))
        get_local(local_id,s58,line_list)
        
def get_disp_local( pid,s58,line_list):    
    dist_local_list = s58.get_disp_local(pid)       
    for info in dist_local_list:
        dlocal_id =info.getDispLocalID()
        pid = info.getPID()
        local_name = info.getLocalName()
        depth= info.getDepth()
        fullpath = info.getFullPath()
        order = info.getOrder()
        local_id = info.getLocalID()
        listname = info.getListName()
        type_val = info.getType()
        isvisible = info.getIsVisible()
        longitude = info.getLongitude()
        latitude = info.getLatitude()
        reserved = info.getReserved()
        
        if reserved is None:
            reserved = 0
        visible = 0
        if (isvisible):
            visible = 1
        
        param=["%s"%dlocal_id,"%s"%pid,"%s"%local_name,"%s"%local_id,"%s"%fullpath,"%s"%listname,"%s"%isvisible,"%s"%depth,"%s"%order,"%s"%type_val,"%s"%longitude,"%s"%latitude,"%s"%reserved]
        line_list.append('\t'.join(param))
        get_disp_local(dlocal_id,s58,line_list)
        
#logic
def execute(date):
    s58=CMCService()

    #get_cmc(s58,"displocal",date)
    try:
        pass
        get_cmc(s58,"dispcategory",date)
    except Exception,e:
        print 'get_dispcate:',e
    try:
        pass
        get_cmc(s58,"category",date)
    except Exception,e:
        print 'get_cate:',e
    try:
        pass
        get_cmc(s58,"local",date)
    except Exception,e:
        print 'get_local:',e
    try:
        pass
        get_cmc(s58,"displocal",date)
    except Exception,e:
        print 'get_displocal:',e

def main():
 
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date=format_date(sys.argv[1])
        end_date=start_date
   elif len(sys.argv)==3:
        start_date=format_date(sys.argv[1])
        end_date=format_date(sys.argv[2])
   stat_date=start_date
   while stat_date>=start_date and stat_date<=end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        #
        execute( stat_date) 
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date=var_date(stat_date)

if __name__=='__main__':
    main()
